{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture 9: Modules, packages and SageMath core development\n", "**References:**\n", "* [Python modules and packages](https://docs.python.org/3/tutorial/modules.html#packages)\n", "* [Python packaging user guide](https://packaging.python.org/en/latest/)\n", "* [SageMath developer's guide](https://doc.sagemath.org/html/en/developer/)\n", "\n", "**Summary:**
\n", "In this lecture we discuss how (and why) to put code into **Python modules** and **Python packages**, and how to install the latter on your system. In the second part, I show a practical example of the steps necessary to contribute to the code of SageMath itself." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python modules and packages\n", "In the previous lecture we saw that one way to share code is to save it to a ``.sage``-file, and run it using ``load``. This is quick to set up and works reasonably in many use cases, but it has some drawbacks (that we discuss below). These can be avoided using **modules** and **packages** in Python.\n", "\n", "### Python modules\n", "One disadvantage when using ``load`` is that it transfers all variable and function names from the loaded file into the current session (of Python or SageMath). In particular, this overwrites existing functions, which can create problems e.g. if you want to use multiple code files using the same function name.\n", "\n", "To avoid this, you can instead store code inside a file with ending ``.py`` (which defines a **Python module**), and then **import** this file. Instead of loading all function names into the current session, this will keep them bundled up inside a module, and you can then access them as shown below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "* Create a file ``basics.py`` in the folder of the current notebook, and save the following text inside (similar to the ``.sage`` files we had before). If you feel lazy, you can also download the file [here](https://johannesschmitt.gitlab.io/mat007/basics.py)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def is_prime(n):\n", " for m in range(2, n):\n", " if n % m == 0:\n", " return False\n", " return True\n", "\n", "def one_third():\n", " return 1/3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Import it as a module using\n", "```\n", "import basics\n", "```\n", "* Run the function ``is_prime`` in an example of your choice, accessing it via ``basics.is_prime``." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution (click to expand)\n", " \n", "```\n", "import basics\n", "basics.is_prime(8)\n", "> False\n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some remarks about the example above:\n", "* First, note that the ``is_prime`` function from the modulie ``basics`` has not overwritten the default ``is_prime`` function in SageMath." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "is_prime == basics.is_prime" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* If you *do* want to import some function into the namespace of the current session, you can do it as follows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from basics import is_prime" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "is_prime == basics.is_prime" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Finally, it is both possible to import a function (or class) giving it a custom name, or to import *all* names from a given module." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from basics import is_prime as is_p" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "is_p(7)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from basics import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One issue to be aware of is that code stored in a ``.py`` file is interpreted as *Python* code. A first consequence is that e.g. numbers you type in this code will be interpreted as Python ``int`` or ``float`` values. Therefore, the function ``one_third`` above, which returns ``1/3``, will actually return ``int(1)/int(3)`` which gives a ``float``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "one_third()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, you need to use e.g. ``**`` instead of ``^`` for exponentiation. Moreover, functions (like ``factorial``) that are part of SageMath will not automatically be available and need to be imported *inside the new Python module*. To get the line of code that you need to add for this (traditionally at the beginning of the ``.py`` file) you can use the function ``import_statements`` in your SageMath session:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import_statements(factorial)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "Say we want to have a function computing ``1/3`` as a ``Rational``. The following code is a first attempt:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def better_one_third():\n", " return Integer(1)/Integer(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Add the code above to the file ``basics.py``. Restart the kernel of the notebook (via ``Kernel -> Restart`` in the menu) and import basics again. Check that when trying to call this function, we obtain an error message since ``Integer`` is not known.
\n", "*Remark:* Note that restarting the kernel is really necessary: the ``import`` will not overwrite a module that was imported before, even if its code changed in the meantime.\n", "* Find the correct line for importing the missing name ``Integer`` and add it to ``basics.py``. Then restart the kernel, import the module and check that now the function ``better_one_third`` works." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution (click to expand)\n", " \n", "Before adding the right import:\n", "```\n", "import basics\n", "basics.better_one_third()\n", ">\n", "---------------------------------------------------------------------------\n", "NameError Traceback (most recent call last)\n", " in ()\n", " 1 import basics\n", "----> 2 basics.better_one_third()\n", "\n", "/home/sage/Desktop/Computer algebra/Notebooks/basics.py in better_one_third()\n", " 11 \n", " 12 def better_one_third():\n", "---> 13 return Integer(1)/Integer(3)\n", "\n", "NameError: name 'Integer' is not defined\n", "```\n", "Finding the right import:\n", "```\n", "import_statements(Integer)\n", "> from sage.rings.integer import Integer\n", "```\n", "After adding this line to the file ``basics.py``:\n", "```\n", "import basics\n", "basics.better_one_third()\n", "> 1/3\n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While it is a bit cumbersome having to import the relevant SageMath-functions as above, it is (as far as I know) the only way to use the strengths of Python modules (and the Python packages below) in SageMath. One tool making it easier is to use the **automatic preparser** of SageMath. This means, you can create a file ``basics.sage`` and write normal Sage-code (that would work inside a SageMath notebook). Then, open a terminal (not a SageMath session!) and type\n", "```\n", "sage --preparse basics.sage\n", "```\n", "The resulting code is correct, but has the disadvantage of containing some inconvenient abbreviations (e.g. for constants).\n", "\n", "
Click here for the preparsed version of the original code block above\n", "\n", "```\n", "# This file was *autogenerated* from the file basics_for_preparsing.sage\n", "from sage.all_cmdline import * # import sage library\n", "\n", "_sage_const_2 = Integer(2); _sage_const_0 = Integer(0); _sage_const_1 = Integer(1); _sage_const_3 = Integer(3)\n", "def is_prime(n):\n", " for m in range(_sage_const_2 , n):\n", " if n % m == _sage_const_0 :\n", " return False\n", " return True\n", "\n", "def one_third():\n", " return _sage_const_1 /_sage_const_3 \n", "```\n", "\n", "
\n", "\n", "For more information see [this guide](https://doc.sagemath.org/html/en/developer/coding_in_python.html#sage-preparsing)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python packages\n", "For bigger projects, it is often convenient to be able to split the code in multiple files (containing different parts of the project). To bundle these, one can combine them into a **Python package**. \n", "\n", "To get our hands on an example, you can download [this zip file](https://johannesschmitt.gitlab.io/mat007/testpackage.zip) and unpack it (in all common operating systems: do a right-click and select \"Extract all\" or something similar). You should get a folder structure as follows:\n", "```\n", "testpackage/\n", "├── LICENSE\n", "├── README.md\n", "├── setup.py\n", "└── testpack\n", " ├── __init__.py\n", " ├── advanced.py\n", " └── basics.py\n", "```\n", "Ignoring the files ``LICENSE`` etc for now, the actual Python package is ``testpack``. In general, such a package is essentially a folder containing\n", "* a file ``__init__.py``\n", "* some Python modules, which can either be ``.py``-files or further sub-packages\n", "\n", "Here the ``__init__.py``-file mostly has a dummy function (allowing the folder to be recognized as a package). However, it can contain some Python code, which is executed when ``testpack`` is first imported. Let's try it out and make some comments.\n", "\n", "Make sure that the folder ``testpackage`` is contained in the same folder as the current notebook. Then we can load the package ``testpack`` as follows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import testpackage.testpack as testpack" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(testpack)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the package is *first* imported, all code contained in the ``__init__.py`` file is run (inside the module). In our case, the ``__init__.py`` file contains the following lines:\n", "```\n", "from .advanced import my_favorite_function as myfavfunc\n", "from .basics import scalar_product\n", "```\n", "Note that above we do a **relative import**: the ``.`` stands for the current directory of ``__init__.py``, and so ``.advanced`` stands for the file ``advanced.py`` located in the same folder as ``__init__.py``.\n", "\n", "Typing ``testpack.`` + ``Tab`` you can check that the module ``testpack`` now contains\n", "* the sub-modules ``advanced`` and ``basic``, and\n", "* the functions ``myfavfunc`` and ``scalar_product`` which were imported in the ``__init__.py`` file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "testpack." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So in practice, you can use the ``__init__.py``file to determine which functions will be loaded into the session when the user types \n", "```\n", "from testpack import *\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "Look at the code contained in ``advanced`` and ``basics``, test some of the functions below and try to understand what each line does." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution (click to expand)\n", " \n", "There is not a well-defined solution to this exercise, but here are some more phenomena to notice:\n", "\n", "* As before we have that the code is interpreted as Python code, so ``testpack.advanced.one_third()`` returns ``0.3333333333333333``. \n", "* Both ``advanced.py`` and ``basics.py`` contain a definition of a function ``my_favorite_function``. Using the structure of modules, these stay nice and separate:\n", "```\n", "testpack.advanced.my_favorite_function()\n", "> 4/3\n", "testpack.basics.my_favorite_function()\n", "> 0\n", "```\n", "* The different files can import from each other (with some care!): \n", " * the module ``advanced`` imports the function ``one_third`` from ``basics``\n", " * inside the function ``scalar_product`` we import ``multiply`` from ``advanced``\n", " Here it's important that we *cannot* import ``multiply`` directly at the start of ``advanced.py``. This leads to a **circular import**, which we have to avoid. Since the code inside the function definitions is not executed, we are good.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Installing and distributing packages\n", "#### Getting the package ready for installation\n", "For the Python package ``testpack`` above, there is one drawback: to import it, it is most convenient to run the SageMath console or notebook inside the folder containing ``testpack`` (otherwise the command ``import testpack`` will give an error). This can be solved by **installing the package**, effectively adding it permanently to the list of \"known modules\" of your SageMath installation. \n", "\n", "To make this possible, we put the folder ``testpack`` into a directory ``testpackage`` with several other files. In more detail, these are:\n", "\n", "* ``setup.py``: It contains instructions for the [setuptools](https://en.wikipedia.org/wiki/Setuptools) module of Python, which takes care of the installation. In the file we provide some basic information about the package (such as name, author, a short description etc). An important variable is ``packages`` which includes the path (relative to ``setup.py``) of the actual Python package we want to install.\n", "* ``README.md``: For a longer description, it is customary to provide such a readme file. Here ``.md`` stands for Markdown, the same language we use for the text/formulas/pictures in Jupyter notebooks. This description is also input in the setup instructions above via a short script in ``setup.py`` loading its text into the parameter ``long_description``.\n", "* ``LICENSE``: This file contains the text of a possible [software license](https://en.wikipedia.org/wiki/Software_license) that you want to use when distributing your code (see below).\n", "\n", "#### The Python package manager pip\n", "With these preparations in place, we can install ``testpack`` via the Python package manager [pip](https://en.wikipedia.org/wiki/Pip_(package_manager)). For this, navigate with a terminal into the folder ``testpackage`` (not ``testpack``!) and type\n", "```\n", "sage -pip install .\n", "```\n", "Here we use ``sage -pip`` to use the version of ``pip`` associated with the Python installation used by SageMath, and ``.`` again stands for the current directory (containing ``setup.py``)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "* Install the package ``testpack`` as described above.\n", "* Navigate with your terminal into a folder *not* containing the ``testpack`` folder.\n", "* Open a SageMath session, run the command ``import testpack`` and execute one of the functions from that package." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some variants of the command above:\n", "```\n", "sage -pip install -e .\n", "```\n", "Installs the package in **editable mode**. This means, if you change the code inside ``testpack`` it will change the behaviour of the module (with code ``sage -pip install .`` above you save a copy of the module at the time of installation, which is not changed when you modify the original code). This editable option is particularly useful if you are still actively working on the code of the package.\n", "```\n", "sage -pip install . --upgrade\n", "```\n", "If you already have a previous version installed, you can use this to upgrade to the new one." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Revisiting doctests\n", "Once you installed the package, it is also possible to run any of the doctests that you included. You should run the ``sage -t`` command on the folder ``testpack`` containing the code files.\n", "```\n", "sage -t testpackage/testpack\n", "```\n", "Note that to make this work, your doctests should always start by importing the relevant functions from the package, like the following doctest of ``scalar_product``:\n", "```\n", " EXAMPLES::\n", " \n", " sage: from testpack.basics import scalar_product\n", " sage: scalar_product([1,2], [3,4])\n", " 11\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### The Python package indey PyPI\n", "One final great feature about pip is that it is by default connected to the [Python package index (PyPI)](https://pypi.org/). This is an online database of Python packages, and to install a package ``foo`` from there, you just need to type\n", "```\n", "sage -pip install foo\n", "```\n", "For our beloved test package above, I did not upload it to PyPI itself, but (following [these instructions](https://packaging.python.org/en/latest/tutorials/packaging-projects/)) I uploaded it to a test-verion of PyPI. Thus, from a console anywhere you can install it using the command\n", "```\n", "sage -pip install -i https://test.pypi.org/simple/ testpackmath007\n", "```\n", "*Remark:* As you see I had to change the name to ``testpackmat007`` since, maybe not unsurprisingly, the very creative name ``testpack`` was already taken ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary: the right format for your code\n", "Here we provide again an overview over the strengths and weaknesses of various ways of storing your code:\n", "* **Jupyter notebooks** are nice for short pieces of code with some additional explanatory text and examples\n", "* **Sage files** are great for projects of medium size, where the user wants to load all relevant functions into their session\n", "* **Python files** allow to create a separate namespace, avoiding collisions with user-defined functions, but they require that you write pure Python code and import relevant SageMath functions by hand\n", "* **Python packages** are the professional standard for projects of greater complexity and can use the Python package index for easy distribution and installation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A panorama of further tools for development\n", "* When editing your code files, you can use the versioning software [git](https://en.wikipedia.org/wiki/Git) to\n", " * keep a record of previous versions of your code\n", " * synchronize your local files with some online repository (like [gitlab](https://gitlab.com/)) to allow multiple people to work on them\n", "* On platforms like gitlab, you also have access to tools for [continuous integration](https://en.wikipedia.org/wiki/Continuous_integration), e.g. a script which runs all doctests of your code whenever you create a new version. In addition, there are tools like [airspeed velocity](https://github.com/airspeed-velocity/asv) which automatically check the speed of the code on a set of example computations, so that you see whether your changes made things faster or slower.\n", "* You can use [sphinx](https://www.sphinx-doc.org/en/master/) to create nice documentation pages for your code (such as [this one](https://doc.sagemath.org/html/en/reference/rings_standard/sage/rings/integer_ring.html)). They are created by putting the docstrings of your functions into some nice, readable format." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## SageMath core development - a practical example (a.k.a. showing my homework)\n", "### The task\n", "Recall from the first lecture the following disappointing performance of SageMath:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "M = matrix([[17,2,-4,9],[-13,2,8,3],[6,1,-1,4],[5,5,-2,2]])\n", "P = M.characteristic_polynomial()\n", "P" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "S = ZZ[x].quotient_ring(P); S" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "S.is_integral_domain()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The problem was that the class of ``S`` did not have a good implementation of the function ``is_integral_domain``. \n", "I gave myself the exercise to write a suitable version of the ``is_integral_domain`` function, and get it added to SageMath. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### My solution\n", "You can see the results of my effort under the following [trac ticket of SageMath](https://trac.sagemath.org/ticket/33568). To see the actual code changes I proposed, you can click on the link to the [branch](https://git.sagemath.org/sage.git/commit?id=3dd4e6b4702021860184fe8e775c5faa370d9bb4) which I created. \n", "\n", "Below is the relevant function. Note that in this case ``self`` will be the ring in question, which is of the form\n", "$$\n", "R[x]/(f(x))\n", "$$\n", "where $R$ (=``self.base_ring()``) is any commutative ring with $1$ and $f$ (=``self.modulus()``) is a nonzero element of $R[x]$ with leading coefficient which is a unit in $R$.\n", "\n", "After executing the cell below, the rings will know this better function ``is_integral_domain``, so when you run the cell above again, it will give the correct result." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def is_integral_domain(self, proof = True):\n", " \"\"\"\n", " Return whether or not this quotient ring is an integral domain.\n", "\n", " EXAMPLES::\n", "\n", " sage: R. = PolynomialRing(ZZ)\n", " sage: S = R.quotient(z^2 - z)\n", " sage: S.is_integral_domain()\n", " False\n", " sage: T = R.quotient(z^2 + 1)\n", " sage: T.is_integral_domain()\n", " True\n", " sage: U = R.quotient(-1)\n", " sage: U.is_integral_domain()\n", " False\n", " sage: R2. = PolynomialRing(R)\n", " sage: S2 = R2.quotient(z^2 - y^3)\n", " sage: S2.is_integral_domain()\n", " True\n", " sage: S3 = R2.quotient(z^2 - 2*y*z + y^2)\n", " sage: S3.is_integral_domain()\n", " False\n", "\n", " sage: R. = PolynomialRing(ZZ.quotient(4))\n", " sage: S = R.quotient(z-1)\n", " sage: S.is_integral_domain()\n", " False\n", "\n", " TESTS:\n", "\n", " Here is an example of a quotient ring which is not an integral\n", " domain, even though the base ring is integral and the modulus is\n", " irreducible::\n", "\n", " sage: B = ZZ.extension(x^2 - 5, 'a')\n", " sage: R. = PolynomialRing(B)\n", " sage: S = R.quotient(y^2 - y - 1)\n", " sage: S.is_integral_domain()\n", " Traceback (most recent call last):\n", " ...\n", " NotImplementedError\n", " sage: S.is_integral_domain(proof = False)\n", " False\n", "\n", " The reason that the modulus y^2 - y -1 is not prime is that it\n", " divides the product\n", " (2*y-(1+a))*(2*y-(1-a)) = 4*y^2 - 4*y - 4.\n", "\n", " Unfortunately, the program above is already unable to determine\n", " that the modulus is irreducible.\n", " \"\"\"\n", " from sage.categories.all import IntegralDomains\n", " if self.category().is_subcategory(IntegralDomains()):\n", " return True\n", " ret = self.base_ring().is_integral_domain(proof)\n", " if ret:\n", " try:\n", " irr = self.modulus().is_irreducible()\n", " if not irr:\n", " # since the modulus is nonzero, the condition of the base ring being an\n", " # integral domain and the modulus being irreducible are\n", " # necessary but not sufficient\n", " ret = False\n", " else:\n", " from sage.categories.gcd_domains import GcdDomains\n", " if self.base_ring() in GcdDomains():\n", " # if the base ring is a GCD domain, the conditions are sufficient\n", " ret = True\n", " else:\n", " raise NotImplementedError\n", " except NotImplementedError:\n", " if proof:\n", " raise\n", " else:\n", " ret = False\n", "\n", " if ret:\n", " self._refine_category_(IntegralDomains())\n", " return ret\n", "\n", "# Adding this function to existing class via monkey patching\n", "from sage.rings.polynomial.polynomial_quotient_ring import PolynomialQuotientRing_generic\n", "PolynomialQuotientRing_generic.is_integral_domain = is_integral_domain" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "R. = PolynomialRing(ZZ)\n", "S = R.quotient(z^2 - z)\n", "S.is_integral_domain()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "T = R.quotient(z^2 + 1)\n", "T.is_integral_domain()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Solution steps\n", "The abstract process for contributing code to SageMath is described in the [official developer guide](https://doc.sagemath.org/html/en/developer/index.html). Below I give a summary of the concrete steps I had to take:\n", "* To change the source code of SageMath, one needs to first [download this code](https://doc.sagemath.org/html/en/developer/walk_through.html#obtaining-and-compiling-the-sage-source-code), and [compile SageMath from it](https://github.com/sagemath/sage/#readme). Many of the usual installations will give you access to a pre-compiled version, which is not enough to do SageMath development. For me, working on Windows, the easiest way to do this compilation was to work with the [Windows subsystem for Linux](https://wiki.sagemath.org/SageWindows#Windows_Subsystem_for_Linux), which is an installation of Linux running inside Windows.\n", "* I made changes to the source code (mostly in the file ``/src/sage/rings/polynomial/polynomial_quotient_ring.py``), adding the function ``is_integral_domain`` above. Note that the function has a documentation with several examples.\n", "* Using this updated version of SageMath, I ran all doctests in the source files of SageMath itself, and encountered an error! It turns out that my changes broke some expected behaviour in an obscure little corner of the software dealing with splitting algebras (whatever that is). This was fixed using the code\n", "```\n", " from sage.categories.all import IntegralDomains\n", " if self.category().is_subcategory(IntegralDomains()):\n", " return True\n", "```\n", " Note that I would not have found this in a million years without doctests! \n", "* I pushed my changes to a new **branch** on the [trac server of SageMath](https://trac.sagemath.org/) where the development happens. For this I needed to create an account there, and install the [git-trac software](https://doc.sagemath.org/html/en/developer/git_trac.html) on my computer. \n", "* I got some helpful feedback from Vincent Delecroix, one of the main developers of SageMath, and I changed the code accordingly.\n", "* Once this review was finished, the code was marked ready to be merged into the main (development) version of SageMath (this happened a few days later).\n", "* This means that starting from the [next version of SageMath](https://trac.sagemath.org/wiki/ReleaseTours/sage-9.6), which is scheduled to release sometime later this year, it will be possible to use the function above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assignments\n", "#### Exercise\n", "Recall that in a previous lecture we had some code for a class ``Rectangle`` implementing rectangles with sides parallel to the $x$ and $y$-axes. Similarly, one could write a class ``Circle`` implementing circles in the plane (e.g. with given center and radius).\n", "\n", "* Write a small Python package, containing files ``rectangles.py`` and ``circles.py`` which contain classes for such rectangles and circles. Add methods so that for any rectangle, one can compute the [circumscribed circle](https://en.wikipedia.org/wiki/Circumscribed_circle) and so that for any circle one can compute the (unique) \"insquare\", i.e. the unique square with corners on the circle (and sides parallel to $x,y$-directions as before). Make sure that at least some of your functions contain documentation with doctests.\n", "* Install the package in your system.\n", "* Run the doctests." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
Solution (click to expand)\n", " \n", "You find one possible solution for this package [here](https://johannesschmitt.gitlab.io/mat007/shapespackage.zip). Below is the code for the files ``rectangles.py``:\n", "```\n", "from sage.functions.other import sqrt\n", "\n", "class Rectangle:\n", " def __init__(self, xmin, xmax, ymin, ymax):\n", " self.xmin = xmin\n", " self.xmax = xmax\n", " self.ymin = ymin\n", " self.ymax = ymax\n", " \n", " def __repr__(self):\n", " return 'Rectangle [{}, {}] x [{}, {}]'.format(self.xmin, self.xmax, self.ymin, self.ymax)\n", " \n", " def area(self):\n", " r\"\"\"\n", " Compute the area of the rectangle.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Rectangle\n", " sage: R = Rectangle(0, 4, 2, 3)\n", " sage: R.area()\n", " 4\n", " sage: R = Rectangle(0, 0, 2, 3)\n", " sage: R.area()\n", " 0 \n", " \"\"\"\n", " return (self.xmax-self.xmin)*(self.ymax-self.ymin)\n", " \n", " def is_square(self):\n", " r\"\"\"\n", " Check whether the rectangle is a square.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Rectangle\n", " sage: R = Rectangle(2, 4, 3, 5)\n", " sage: R.is_square()\n", " True\n", " sage: R = Rectangle(2, 4, 3, 6)\n", " sage: R.is_square()\n", " False\n", " \n", " TESTS::\n", " \n", " In the first implementation, the following example caused a\n", " problem, since it returned ``pi == pi`` instead of ``True``.\n", " \n", " sage: from shapespack import *\n", " sage: R = Rectangle(0, pi, 0, pi)\n", " sage: R.is_square()\n", " True\n", " \"\"\"\n", " return bool((self.xmax-self.xmin) == (self.ymax-self.ymin))\n", " \n", " def center(self):\n", " r\"\"\"\n", " Compute the center of mass of the rectangle.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Rectangle\n", " sage: R = Rectangle(-3, -2, 0, 8)\n", " sage: R.center()\n", " (-5/2, 4)\n", " \"\"\"\n", " return ((self.xmin + self.xmax)/2, (self.ymin + self.ymax)/2)\n", " \n", " def circumcircle(self):\n", " r\"\"\"\n", " Compute the circle through the four vertices of the\n", " rectangle.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Rectangle\n", " sage: R = Rectangle(-3, -2, 0, 8)\n", " sage: R.circumcircle()\n", " Circle around (-5/2, 4) of radius 1/2*sqrt(65)\n", " \"\"\"\n", " from .circles import Circle\n", " center = self.center()\n", " x, y = center\n", " radius = sqrt((x-self.xmin)**2 + (y-self.ymin)**2)\n", " return Circle(center, radius)\n", "```\n", "and ``circles.py``:\n", "```\n", "from sage.symbolic.ring import SR\n", "from sage.functions.other import sqrt\n", "\n", "\n", "class Circle:\n", " def __init__(self, center, radius):\n", " self.center = center\n", " self.radius = radius\n", " \n", " def __repr__(self):\n", " return f'Circle around {self.center} of radius {self.radius}'\n", " \n", " def area(self):\n", " r\"\"\"\n", " Computes the area of the circle.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Circle\n", " sage: C = Circle((2,3), 5)\n", " sage: C\n", " Circle around (2, 3) of radius 5\n", " sage: C.area()\n", " 25*pi\n", " \"\"\"\n", " return SR.pi() * self.radius**2\n", " \n", " def insquare(self):\n", " r\"\"\"\n", " Compute the unique square with vertices on the circle\n", " and sides parallel to the x,y axes.\n", " \n", " EXAMPLES::\n", " \n", " sage: from shapespack import Circle\n", " sage: C = Circle((2,3), 3*sqrt(2)); C\n", " Circle around (2, 3) of radius 3*sqrt(2)\n", " sage: R = C.insquare(); R\n", " Rectangle [-1, 5] x [0, 6]\n", " sage: R.circumcircle()\n", " Circle around (2, 3) of radius 3*sqrt(2)\n", " \"\"\"\n", " from .rectangles import Rectangle\n", " x,y = self.center\n", " r = self.radius\n", " sq2 = sqrt(2)\n", " return Rectangle(x-r/sq2, x+r/sq2, y-r/sq2, y+r/sq2)\n", "```\n", "If you have a terminal inside the folder ``shapespackage``, you can install it and run the doctests as follows:\n", "```\n", "sage -pip install -e .\n", "sage -t shapespack\n", "> too few successful tests, not using stored timings\n", "Running doctests with ID 2022-05-17-07-23-46-a49dd1e2.\n", "Using --optional=bliss,ccache,cmake,coxeter3,dochtml,mcqd,primecount,sage,tdlib\n", "Doctesting 3 files.\n", "sage -t shapespack/circles.py\n", " [8 tests, 0.02 s]\n", "sage -t shapespack/rectangles.py\n", " [19 tests, 0.02 s]\n", "sage -t shapespack/__init__.py\n", " [0 tests, 0.00 s]\n", "----------------------------------------------------------------------\n", "All tests passed!\n", "----------------------------------------------------------------------\n", "Total time for all tests: 1.4 seconds\n", " cpu time: 0.0 seconds\n", " cumulative wall time: 0.0 seconds\n", "```\n", "\n", "
" ] } ], "metadata": { "kernelspec": { "display_name": "SageMath 9.1", "language": "sage", "name": "sagemath" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }